package com.hzz.framework.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.math.RoundingMode;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.util.Date;

@Slf4j
public class FileUtil {
    private static DecimalFormat df = null;

    static {
        // 设置数字格式，保留一位有效小数
        df = new DecimalFormat("#0.0");
        df.setRoundingMode(RoundingMode.HALF_UP);
        df.setMinimumFractionDigits(1);
        df.setMaximumFractionDigits(1);
    }

    public static void mkdirs(String filePath) throws Exception {
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    public static String getPath() {
        String path = null;
        try {
            URL url = FileUtil.class.getProtectionDomain().getCodeSource().getLocation();
            path = URLDecoder.decode(url.getPath(), "utf-8");// 转化为utf-8编码
            if (path.endsWith(".jar")) {// 可执行jar包运行的结果里包含".jar"
                // 截取路径中的jar包名
                path = path.substring(0, path.lastIndexOf("/") + 1);
            }
            File file = new File(path);
            path = file.getAbsolutePath();//得到windows下的正确路径
        } catch (Exception e) {
            log.error("文件路径获取错误!", e);
        }
        return path;
    }

    /**
     * 获取文件后缀
     *
     * @param fileName
     * @return
     */
    public static String getFileExt(String fileName) {
        int pos = fileName.lastIndexOf(".");
        if (pos > -1) {
            String temp = fileName.substring(pos + 1).toLowerCase();
            pos = temp.indexOf("?");
            if (pos > -1) {
                return temp.substring(0, pos);
            }
            return temp.trim().replaceAll("\"", "");
        }
        return "";
    }

    /**
     * 删除文件
     *
     * @param filePath
     */
    public static void deleteFile(String filePath) {
        if (ValidatorUtil.notEmpty(filePath)) {
            File file = new File(filePath);
            if (file.exists()) {
                file.delete();
            }
        }
    }

    public static String readfile(String filePath) {
        StringBuffer buffer = new StringBuffer();
        try {
            File file = new File(filePath);
            InputStream input = new FileInputStream(file);
            byte[] bytes = new byte[1024*1024];
            for (int n; (n = input.read(bytes)) != -1; ) {
                buffer.append(new String(bytes, 0, n, StandardCharsets.UTF_8));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    public static String getResourcePath(String fileName) {
        try {
            return getPath() + fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }

    public static void copyDir(String oldPath, String newPath) throws IOException {
        File file = new File(oldPath);
        File newFileDir = new File(newPath);
        if (!(newFileDir).exists()) {
            (newFileDir).mkdir();
        }
        String fileName = file.getName();
        String[] filePath = file.getParentFile().list();
        for (int i = 0; i < filePath.length; i++) {
            if ((new File(oldPath + File.separator + filePath[i])).isDirectory()) {
                copyDir(oldPath + File.separator + filePath[i], newPath + File.separator + filePath[i]);
            }
            if (new File(oldPath + File.separator + filePath[i]).isFile()) {
                copyFile(oldPath + File.separator + filePath[i], newPath + File.separator + filePath[i]);
            }
        }
    }

    public static void copyFile(String oldPath, String newPath) throws IOException {
        File oldFile = new File(oldPath);
//        if (!("jpg".equalsIgnoreCase(getFileExt(oldFile.getName())) || "png".equalsIgnoreCase(getFileExt(oldFile.getName())) || "pcm".equalsIgnoreCase(getFileExt(oldFile.getName())))) {
//            fileCount.getAndAdd(1);
//        }
        File file = new File(newPath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        if (file.exists()) {
            return;
        }
        FileInputStream in = new FileInputStream(oldFile);
        FileOutputStream out = new FileOutputStream(file);
        byte[] buffer = new byte[2 * 1024 * 1024];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        in.close();
        out.close();
    }

    /**
     * 格式化文件大小
     */
    public static String getFormatFileSize(long length) {
        double size = ((double) length) / (1 << 30);
        if (size >= 1) {
            return df.format(size) + "GB";
        }
        size = ((double) length) / (1 << 20);
        if (size >= 1) {
            return df.format(size) + "MB";
        }
        size = ((double) length) / (1 << 10);
        if (size >= 1) {
            return df.format(size) + "KB";
        }
        return length + "B";
    }

    public static InputStream getFileAsInputStream(String filePath) throws Exception {
        InputStream inputStream = null;
        URL url = ResourceUtils.getURL(filePath);
        if (ResourceUtils.isJarURL(url)) {
            if (filePath.startsWith("classpath:")) {
                inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath.substring("classpath:".length()));
            } else {
                inputStream = url.openStream();
            }
        } else {
            inputStream = new FileInputStream(ResourceUtils.getFile(filePath));
        }
        return inputStream;
    }

    public static void closeStream(InputStream inputStream){
        try {
            if(inputStream!=null){
                inputStream.close();
            }
        } catch (Exception e) {
        }
    }

    /**
     * 获取文件名称(不包含扩展名)
     *
     * @param fileName
     * @return
     */
    public static String getFileName(String fileName) {
        int pos = fileName.lastIndexOf(".");
        if (pos > -1) {
            String temp = fileName.substring(pos + 1).toLowerCase();
            pos = temp.indexOf("?");
            if (pos > -1) {
                return temp.substring(0, pos);
            }
            return temp.trim().replaceAll("\"", "");
        }
        return "";
    }

    public static String nowDate() {
        return DateUtil.getDateTimeStr(new Date());
    }
}
